package com.example.fisttestproject;

import android.content.Context;
import android.os.Bundle;

import com.example.fisttestproject.database.AppDatabase;
import com.example.fisttestproject.entity.User;
import com.example.fisttestproject.util.Const;
import com.example.fisttestproject.util.Util;
import com.google.android.material.snackbar.Snackbar;

import androidx.appcompat.app.AppCompatActivity;

import android.util.Log;
import android.view.View;

import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.room.Room;

import com.example.fisttestproject.databinding.ActivityMainBinding;
import com.yanzhenjie.andserver.AndServer;
import com.yanzhenjie.andserver.Server;

import android.view.Menu;
import android.view.MenuItem;

import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HttpsURLConnection;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private AppBarConfiguration appBarConfiguration;
    private ActivityMainBinding binding;

    private Server mServer;


    // TODO 全局
    public static AppDatabase appDatabase;


    @Override
    protected void onStart() {
        super.onStart();

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        AndServiceInit.start(this);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        setSupportActionBar(binding.toolbar);

        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
        appBarConfiguration = new AppBarConfiguration.Builder(navController.getGraph()).build();
        NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);

        binding.fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
        // 本地模拟请求
        localRequest();
    }

    private void localRequest() {
        Thread thread = new Thread(() -> {

            // 启动http服务
//            startHttpServer();
//            // 模拟请求
            OkHttpClient client = new OkHttpClient();
            // 测试db 存储
//            AppDatabase db = Room.databaseBuilder(getApplicationContext(),
//                    AppDatabase.class, "test").build();


            AppDatabase db = AppDatabase.getDatabase(getApplicationContext());
            List<User> userList = new ArrayList<>();
            User user = new User();
            user.setId(1);
            user.setName("test");
            userList.add(user);
            user = new User();
            user.setId(2);
            user.setName("test2");
            userList.add(user);
//            db.userDao().insertAll(user);

            List<User> all = db.userDao().getAll();
            all.stream().forEach(System.out::println);

            db.getOpenHelper().setWriteAheadLoggingEnabled(true);

            while (true) {
                try {

                    // 创建GET请求
                    Request request = new Request.Builder()
                            .url("http://localhost:"+Const.GLOBAL.SERVER_PORT+"/user/getAll") // 替换为你的API地址
                            .build();

                    try (Response response = client.newCall(request).execute()) {
                        if (!response.isSuccessful()) {
                            System.out.println("请求失败： " + response);
                        } else {
                            String responseBody = response.body().string();
                            System.out.println("响应内容： " + responseBody);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                try {
                    Thread.sleep(1000);
                    System.out.println(new Date());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        thread.start();
    }

//    private void startHttpServer() {
//        server = new AppServer(SERVER_PORT);
//        try {
//            server.start();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        System.out.println("服务启动完成");
//    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onSupportNavigateUp() {
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
        return NavigationUI.navigateUp(navController, appBarConfiguration)
                || super.onSupportNavigateUp();
    }

    @Override
    protected void onStop() {
        super.onStop();

    }

}